const express = require("express")
const User = require("./model/user")
const router = express.Router()


router.get("/", function (req, res) {
    res.render("index.html", {
        user: req.session.loginUser
    })
})


router.get("/register", function (req, res) {
    res.render("register.html")
})

router.post("/register", function (request, respone, next) {
    let sendError = (error) => {
        next(error)
    }
    let body = request.body
    User.checkEmailExist(body.email)
        .then(() => {
            return User.checkNicknameExist(body.nickname)
        }, sendError)
        .then(() => {
            //注册
            User.register(body)
                .then(res => {
                    return respone.status(200).send("ok");
                }, sendError)
        }, sendError)
})


router.get("/login", function (req, res) {
    res.render("login.html")
})
router.post("/login", function (request, respone, next) {
    let sendError = (error) => {
        next(error)
    }
    User.login(request.body)
        .then(res => {
            request.session.loginUser = res
            respone.status(200).send("登录成功")
        }, sendError)
})

router.get("/logOut", function (request, respone) {
    request.session.loginUser = null
    respone.redirect("/login")
})


router.get("/topics/new", function (request, respone) {
    respone.render("topic/new.html", {
        user: request.session.loginUser
    })
})


module.exports = router;